// function work (deadline) {
//   if (deadline.timeRemaining() > 0) {
//     // 记录每帧的空余时间，每秒60帧 每帧时间为16ms
//     // 1. 16 - 每帧实行时间 剩余就是空闲时间
//     // 2. 页面长时间没操作时，剩余时间最多50ms
//     console.log(deadline.timeRemaining())
//     // this.timeRemaining.push(deadline.timeRemaining())
//   }
//
//   window.requestIdleCallback(work)
// }
// window.requestIdleCallback(work)

class IdlePerformance {
  constructor () {
    this.t1 = null
    this.t2 = null
    this.timeRemaining = [] // 一分钟内所有帧的剩余时间
    this.statisticsTime = [] // 15分钟内每分钟的剩余时间
  }

  init () {
    const work = (deadline) => {
      if (deadline.timeRemaining() > 0) {
        // 记录每帧的空余时间，每秒60帧 每帧时间为16ms
        // 1. 16 - 每帧实行时间 剩余就是空闲时间
        // 2. 页面长时间没操作时，剩余时间最多50ms
        // console.log(deadline.timeRemaining())
        this.timeRemaining.push({ time: deadline.timeRemaining(), timeout: deadline.didTimeout })
      }

      window.requestIdleCallback(work)
    }
    window.requestIdleCallback(work)
  }

  start (app) {
    this.log = app ? app.log.info : null
    this.log = console.log
    this.timeRemaining = []
    this.statisticsTime = []

    this.init()
    this.statistics()
  }

  statistics () {
    // 每分钟计算一次
    this.t1 = setInterval(() => {
      let sum = 0; let timeoutCount = 0

      if (this.timeRemaining.length > 0) {
        this.timeRemaining.forEach((t) => {
          if (t.timeout) timeoutCount = timeoutCount + 1
          sum += t.time
        })
      }
      this.statisticsTime.push({
        time: new Date().toLocaleString(),
        sum: sum.toFixed(2),
        timeoutCount: timeoutCount, // 超时次数
        allCount: this.timeRemaining.length
      })

      this.timeRemaining = []
    }, 60 * 1000)

    // 每15分钟打印一次
    this.t2 = setInterval(() => {
      if (this.log) {
        this.log('-------------------------------------------')
        for (let i = 0; i < this.statisticsTime.length; i++) {
          const t = this.statisticsTime[i]
          this.log('| ' + t.time + ' | ' + t.sum + ' | ' + t.timeoutCount + ' | ' + t.allCount)
        }
        this.log('-------------------------------------------')
      } else {
        console.table(this.statisticsTime)
      }

      this.statisticsTime = []
    }, 2 * 60 * 1000)
  }

  end () {
    this.timeRemaining = null
    this.statisticsTime = null
    clearInterval(this.t1)
    clearInterval(this.t2)
  }

  currentTime () {
    const date = new Date()
    return date.getFullYear() + '-' +
      (date.getMonth() + 1) + '-' +
      date.getDate() + ' ' +
      date.getHours() + ':' +
      date.getMinutes() + ':' +
      date.getSeconds()
  }
}

export default new IdlePerformance()
